package com.wsz.logistic.controller.admin;

import com.wsz.logistic.bean.Deliverier;
import com.wsz.logistic.bean.Userinfo;
import com.wsz.logistic.common.form.Receiver;
import com.wsz.logistic.common.util.R;
import com.wsz.logistic.common.util.SessionInfo;
import com.wsz.logistic.service.UserinfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/admin/userinfo")
public class UserinfoController extends SessionInfo {
    @Autowired
    private UserinfoService userinfoService;

    @GetMapping("/list")
    public String list(int role, Model model) {
        model.addAttribute("role", role);
        return "admin/userinfo/userinfo-list";
    }


    @GetMapping("/page")
    @ResponseBody
    public R page(int page, int limit, Userinfo userinfo) {
        return userinfoService.getPage(page, limit, userinfo);
    }

    @GetMapping("/edit")
    public String edit(Integer userinfoId, String type, Model model) {
        if (userinfoId != null) {
            model.addAttribute("type", type);
            model.addAttribute("userinfo", userinfoService.getById(userinfoId));
        }
        return "admin/userinfo/userinfo-update";
    }

    @PostMapping(value = {"/update", "/status", "/password"})
    @ResponseBody
    public R update(Receiver receiver) {
        Userinfo userinfo = new Userinfo();
        BeanUtils.copyProperties(receiver, userinfo);
        if (receiver.getDistrict() != null) {
            Deliverier deliverier = new Deliverier();
            deliverier.setDeliverierId(receiver.getUserinfoId());
            deliverier.setDistrict(receiver.getDistrict());
            userinfoService.setDeliverier(deliverier);
        }
        userinfoService.saveOrUpdate(userinfo);
        return R.ok();
    }

    @DeleteMapping("/delete/{userinfoId}")
    @ResponseBody
    public R delete(@PathVariable int userinfoId) {
        userinfoService.deleteById(userinfoId);
        return R.ok();
    }

    @GetMapping("/password")
    public String password() {
        return "admin/userinfo/userinfo-password";
    }

    @GetMapping("/check/password")
    @ResponseBody
    public R checkPassword(Userinfo userinfo) {
        return userinfoService.checkPassword(userinfo);
    }
}
